const gulp = require('gulp');
const $ = require('gulp-load-plugins')(); // 打包基于 gulp 的所有插件
const open = require('open');

// 1、html 任务
gulp.task('htmlmin', function(done) {
    gulp.src('./src/*.html')
        .pipe($.htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('./dist/'))
        .pipe($.connect.reload());
    done();
})

// 2、css 任务
gulp.task('cssmin', function(done) {
    gulp.src('./src/css/*.css')
        .pipe($.cleanCss())
        .pipe($.rename({ suffix: '.min' }))
        .pipe(gulp.dest('./dist/css/'))
        .pipe($.connect.reload());
    done();
})

// 3、js 任务
gulp.task('jsmin', function(done) {
    gulp.src('./src/js/*.js')
        .pipe($.uglify())
        .pipe($.rename({ suffix: '.min' }))
        .pipe(gulp.dest('./dist/js/'))
        .pipe($.connect.reload());
    done();
})

// 静态资源任务
gulp.task('copy', function(done) {
    gulp.src('./src/images/*')
        .pipe(gulp.dest('./dist/images'))
        .pipe($.connect.reload());
    gulp.src('./src/upload/*')
        .pipe(gulp.dest('./dist/upload'))
        .pipe($.connect.reload());
    done();
});

// bootstarp 任务
gulp.task('bt', function(done) {
    gulp.src('./src/bootstrap/**/*')
        .pipe(gulp.dest('./dist/bootstrap'))
        .pipe($.connect.reload());
    done();
})

// 监听任务
// gulp.task('watch', function(done) {
//     gulp.watch('./src/*.html', gulp.series(['htmlmin']))
//     gulp.watch('./src/css/*.css', gulp.series(['cssmin']))
//     gulp.watch('./src/js/*.js', gulp.series(['jsmin']))
//     gulp.watch('./src/bootstrap/**/*', gulp.series(['bt']))
//     gulp.watch('./src/images/*', gulp.series(['copy']))
//     gulp.watch('./src/upload/*', gulp.series(['copy']))
//     done();
// })

// 服务器任务
gulp.task('server', function(done) {
    $.connect.server({
        root: 'dist',
        port: 3000,
        livereload: true
    });
    open('http://localhost:3000');
    gulp.watch('./src/*.html', gulp.series(['htmlmin']));
    gulp.watch('./src/css/*.css', gulp.series(['cssmin']));
    gulp.watch('./src/js/*.js', gulp.series(['jsmin']));
    gulp.watch('./src/bootstrap/**/*', gulp.series(['bt']));
    gulp.watch('./src/images/*', gulp.series(['copy']));
    gulp.watch('./src/upload/*', gulp.series(['copy']));
    done();
})

// 默认任务
gulp.task('default', gulp.series(['server']))